#!/bin/bash

# show the command executed by the script
#set -x

PREFIX="\033[;32mINFO: \033[0m"
SPIKE=/opt/riscv/bin/spike
LIBCACTIO_PATH=./build
RVCC=/opt/riscv/bin/riscv64-unknown-elf-gcc

if [ $# -eq 0 ]; then
	echo "Usage: $0 <CACT source file> options"
	exit 1
fi

mkdir -p ./temp
# substitute the file extension ".cact" with ".ll" in `$1`
asmfile=${1%.cact}-hxd1.s
exefile_hxd1=${1%.cact}-hxd1
# remove the path in `asmfile`
asmfile=${asmfile##*/}
exefile_hxd1=${exefile_hxd1##*/}

echo -e $PREFIX"Compiling CACT file to RV64 ASM..."
./build/compiler $1  -o ./temp/$asmfile $2 $3 $4 $5 $6 $7 $8
if [ $? -ne 0 ]; then
	exit $?
fi

echo -e $PREFIX"Assembling and linking RV64 ASM file to ELF..."
$RVCC ./temp/$asmfile -o ./temp/$exefile_hxd1 -L$LIBCACTIO_PATH -lcactio
if [ $? -ne 0 ]; then
	exit $?
fi

cfile=${1%.cact}.c

# remove the path in `cfile`
cfile=${cfile##*/}

exefile_gcc=${1%.cact}-gcc
exefile_gcc=${exefile_gcc##*/}


echo -e $PREFIX"Generating C code..."
cat ./test/cactio.c $1 > ./temp/$cfile

echo -e $PREFIX"Compiling C file with gcc..."
gcc ./temp/$cfile -o ./temp/$exefile_gcc

if [ $? -ne 0 ]; then
	exit $?
fi

echo -e $PREFIX"Press Enter to start the ELF file from HXD1... "
read -p "> "

# `-s`: show the instruction count
$SPIKE pk -s ./temp/$exefile_hxd1

echo -e $PREFIX"Press Enter to start the ELF file from gcc... "
read -p "> "

./temp/$exefile_gcc
